import { getStoresById, postStoresById } from '../../../services/api';

export default {
  namespace: 'setByMerchant',

  state: {
    data: [],
  },

  effects: {
    *fetch(payload, { call, put }) {
      const storeId = localStorage.getItem('storeId');
      const response = yield call(getStoresById, storeId);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *update({ payload, callback }, { call, put }) {
      const { storeId } = payload;
      const response = yield call(postStoresById, storeId, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    replace(state, action) {
      const { list } = state.data;
      list.splice(action.payload.editableIndex, 1, action.payload.response);
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
          },
        },
      };
    },
  },
};
